<?php


namespace App\Socket\WebSocket\MessageServer;


// 消息处理类型
use App\Common\JsonSendMessage;
use EasySwoole\Component\Timer;
use EasySwoole\EasySwoole\ServerManager;

use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\Socket\AbstractInterface\Controller;
use Swoole\Coroutine;

class WebSocketMessage extends BaseMessage
{
    /**
     * 执行默认方法入口
     */
    public function run()
    {
        //获取客服端发送的消息
        $content = $this->caller()->getArgs();
        if (isset($content[0]['number'])) {
            $this->response()->setMessage(JsonSendMessage::getInstance()->successJson(['msg' => '我是正常回复', 'req' => $content]));
            return false;
        }
//        $this->response()->setMessage('这是 run 方法');
        $client = $this->caller()->getClient();
        // 异步推送, 这里直接 use fd也是可以的
//        TaskManager::getInstance()->async(function () use ($client) {
//
//        });
        go(function () use ($client) {
            $i = 1;
            Timer::getInstance()->loop(5000,function () use ($client){
                $this->sendMessage($client, JsonSendMessage::getInstance()->successJson(['fd' => $client->getFd(), 'time' => date('Y-m-d H:i:s'), 'msg' => '我是定时5秒推送']));
            });
        });
        $this->sendAll();
    }

    // 发送全部消息
    protected function sendAll()
    {
        $server = ServerManager::getInstance()->getSwooleServer();
        Timer::getInstance()->loop(10000, function () use ($server) {
            $conn_list = $server->getClientList(0);
            if ($conn_list) {
                foreach ($conn_list as $fd) {
                    $server->push($fd, JsonSendMessage::getInstance()->successJson('我是定时10秒,全部推送消息'));
                }
            }
        });
    }

}
